<!-- 数据可视化中心-数据准备-数据源基本信息管理 -->
<template>
    <el-container v-loading.fullscreen.lock="fullscreenLoading" class="custom__container">
        <el-aside width="260px">
            <div class="custom__aside">
                <div class="custom__aside-header">
                    <hsa-title-box title="组织团队信息"></hsa-title-box>
                    <el-divider class="custom__aside-divider" </el-divider>
                </div>

                <!-- 列表 -->
                <section class="custom__aside-content">
                    <el-tree style="max-width: 600px" v-bind="treeOption" v-on="treeEvents" />
                </section>
            </div>
        </el-aside>

        <el-main class="custom__main">
            <hsa-adaptive-container>
                <!-- 查询 -->
                <hsa-adaptive-pane>
                    <hsa-title-pane>
                        <hsa-title-pane-item :title="operateTitle">
                            <el-form label-width="100">
                                <hsa-row :gutter="20">
                                    <hsa-col :span="6">
                                        <el-form-item label="组织名称">
                                            <el-input v-model="saveForm.data.organizationName"
                                                :disabled="forbid.organizationName" placeholder="请输入组织名称" />
                                        </el-form-item>
                                        <el-form-item label="团队名称">
                                            <el-input v-model="saveForm.data.teamName" :disabled="forbid.teamName"
                                                placeholder="请输入团队名称" />
                                        </el-form-item>
                                    </hsa-col>

                                    <template #footbar>
                                        <el-button type="default" @click="operate.cancel">取 消</el-button>
                                        <el-button type="primary" @click="operate.save" :disabled="forbid.save">
                                            保 存
                                        </el-button>
                                        <el-button type="danger" @click="operate.delete">删 除</el-button>
                                    </template>
                                </hsa-row>
                            </el-form>
                        </hsa-title-pane-item>
                    </hsa-title-pane>
                </hsa-adaptive-pane>

                <!-- 数据源管理 -->
                <hsa-adaptive-pane auto-height>
                    <hsa-title-pane fill>
                        <hsa-title-pane-item fill>
                            <template #title-suffix>
                                <el-button-group>
                                    <el-button :type="switchover ? 'info' : 'default'" plain
                                        @click="SwitchoverSource">数据源权限</el-button>
                                    <el-button :type="!switchover ? 'info' : 'default'" plain
                                        @click="SwitchoverUser">用户信息</el-button>
                                </el-button-group>
                            </template>

                            <template #toolbar>
                                <el-button type="primary" @click="Temporary">暂存</el-button>
                            </template>
                            <hsa-table v-if="switchover" v-bind="tableOptionSourceList" auto-height></hsa-table>
                            <hsa-table v-else v-bind="tableOptionUserList" auto-height></hsa-table>
                        </hsa-title-pane-item>
                    </hsa-title-pane>
                </hsa-adaptive-pane>
            </hsa-adaptive-container>
        </el-main>
    </el-container>
</template>

<script setup lang="ts">
    import { ref, reactive, computed } from 'vue'
    import { Observable, from, map, mergeMap } from 'rxjs';
    import { ElMessage } from 'element-plus'

    // API
    import {
        ApiDataSourceConfigTeam,
        dataSourceConfigTeamSave,
        type ResponseDataSourceConfigTeam,
        type ParamDataSourceConfigTeamGetDataSourceList,
    } from '~api/DataPreparation'

    // 类型
    import type { HsaTableColumn, HsaTablePaginationProps } from "hsa-ui"

    // 全屏加载
    const fullscreenLoading = ref(false)

    // 目录配置
    const treeOption = reactive({
        data: <ResponseDataSourceConfigTeam.Organization[]>[],
        props: { label: 'label', children: 'teams' },
    })
    const treeEvents = reactive({
        nodeClick(data: ResponseDataSourceConfigTeam.Organization & ResponseDataSourceConfigTeam.Team) {
            saveForm.reset()

            // 团队
            if (data.teamId) {
                saveForm.data.teamId = data.teamId
                saveForm.data.teamName = data.teamName
                const team = treeOption.data.find(item => item.organizationId === data.organizationId)
                if (team) {
                    saveForm.data.organizationId = team.organizationId
                    saveForm.data.organizationName = team.organizationName
                }

                // 数据源获取
                from(new Promise((r) => { r(fullscreenLoading.value = true) }))
                    .pipe(mergeMap(() => TABLE_GET_DATA_SOURCE_LIST()))
                    .subscribe({ complete: () => fullscreenLoading.value = false })
                return
            }

            // 组织
            if (data.organizationId) {
                saveForm.data.organizationId = data.organizationId
                saveForm.data.organizationName = data.organizationName
            }
        }
    })

    // 新增\修改
    const saveForm = reactive({
        data: Object.assign({}, dataSourceConfigTeamSave()),
        reset: () => saveForm.data = Object.assign({}, dataSourceConfigTeamSave())
    })

    // 禁用
    const forbid = reactive({
        organizationName: computed(() => saveForm.data.organizationId ? true : false),
        teamName: computed(() => saveForm.data.teamId ? true : false),
        save: computed(() => saveForm.data.organizationId && saveForm.data.teamId ? true : false)
    })

    // 操作标题
    const operateTitle = computed(() => {
        if (forbid.teamName) return '团队操作'
        if (forbid.organizationName) return '组织操作'
        return '新增团队'
    })

    // 操作
    const operate = reactive({
        cancel: () => saveForm.reset(),
        save: () => from(new Promise((r) => { r(fullscreenLoading.value = true) }))
            .pipe(mergeMap(() => ASIDE_SAVE()))
            .subscribe({
                next(bool) {
                    if (!bool) ElMessage.warning({ message: '非常规保存操作', plain: true })
                },
                complete() {
                    fullscreenLoading.value = false
                }
            })
        ,
        delete: () => from(new Promise((r) => { r(fullscreenLoading.value = true) }))
            .pipe(mergeMap(() => ASIDE_DELETE()))
            .subscribe({
                next(bool) {
                    if (!bool) ElMessage.warning({ message: '非常规删除操作', plain: true })
                },
                complete() {
                    fullscreenLoading.value = false
                }
            })
    })

    // 表格配置
    const tableOptionSourceList = reactive({
        showIndex: true,
        data: <ResponseDataSourceConfigTeam.DataSource[]>[],
        columns: ref<HsaTableColumn[]>([
            { align: 'center', label: '数据源名称', width: 220, prop: 'dataPreparationSourceName' },
            { align: 'center', label: '数据源说明', minWidth: 200, prop: 'preparationSourceDesc' },
            { align: 'center', label: '驱动类型', width: 150, prop: 'dataPreparationSourceType' },
            { align: 'center', label: '数据源IP', width: 260, prop: 'ipAddress' },
            { align: 'center', label: '端口', width: 100, prop: 'port' },
        ]),
        paginationUseExternal: true,
        paginationConfig: ref<HsaTablePaginationProps>({
            total: 0,
            pageSize: 10,
            currentPage: 1
        }),
    })

    // 表格配置
    const tableOptionUserList = reactive({
        showIndex: true,
        data: <ResponseDataSourceConfigTeam.UserInfo[]>[],
        columns: ref<HsaTableColumn[]>([
            { align: 'center', label: '组织机构', minWidth: 200, prop: 'institutionalFramework' },
            { align: 'center', label: '姓名', minWidth: 200, prop: 'userName' },
            { align: 'center', label: '账户', minWidth: 200, prop: 'accountName' },
        ]),
        paginationConfig: ref<HsaTablePaginationProps>({
            total: 0,
            pageSize: 10,
            currentPage: 1
        }),
    })

    // 表格切换
    const switchover = ref(true)

    // 切换数据源
    function SwitchoverSource() {
        switchover.value = true
        from(new Promise((r) => { r(fullscreenLoading.value = true) }))
            .pipe(mergeMap(() => TABLE_GET_DATA_SOURCE_LIST()))
            .subscribe({ complete: () => fullscreenLoading.value = false })
    }

    // 切换用户
    function SwitchoverUser() {
        switchover.value = false
        from(new Promise((r) => { r(fullscreenLoading.value = true) }))
            .pipe(mergeMap(() => TABLE_GET_USER_LIST()))
            .subscribe({ complete: () => fullscreenLoading.value = false })
    }

    // 暂存
    function Temporary() {
        if (switchover.value && tableOptionSourceList.data.length === 0) {
            return ElMessage.warning({ message: '数据源没有数据', plain: true })
        } else if (!switchover.value && tableOptionUserList.data.length === 0) {
            return ElMessage.warning({ message: '用户没有数据', plain: true })
        }

        fullscreenLoading.value = true
        setTimeout(() => {
            fullscreenLoading.value = false
            ElMessage.success({ message: '暂存成功', plain: true })
        }, 3000)
    }

    // API:组织团队信息
    function ASIDE_LIST_TREE() {
        return new Promise<boolean>((resolve, reject) => {
            from(ApiDataSourceConfigTeam.listTree())
                .pipe(map((data) => data))
                .subscribe({
                    next(data) {
                        treeOption.data = data.map((item) => {
                            item.label = item.organizationName
                            if (item.teams) item.teams.map((team) => {
                                team.label = team.teamName
                                team.organizationId = item.organizationId
                                return team
                            })
                            return item
                        })
                    },
                    error(error) {
                        console.error(error)
                        reject(error);
                    },
                    complete() {
                        resolve(true)
                    },
                });
        })
    }

    // API:组织团队保存
    function ASIDE_SAVE() {
        return new Promise<boolean>((resolve, reject) => {
            if (!saveForm.data.organizationName) return resolve(false)
            from(ApiDataSourceConfigTeam.save(saveForm.data))
                .pipe(map((data) => data))
                .pipe(mergeMap((data) => from(ASIDE_LIST_TREE()).pipe(map(() => data))))
                .subscribe({
                    next(data) {
                        ElMessage.success({ message: data, plain: true })
                        saveForm.reset()
                    },
                    error(error) {
                        ElMessage.error({ message: '保存失败', plain: true })
                        console.error(error)
                        reject(error)
                    },
                    complete() {
                        resolve(true)
                    }

                })
        })
    }

    // API:组织团队删除
    function ASIDE_DELETE() {
        return new Promise<boolean>((resolve, reject) => {
            if (!saveForm.data.organizationId) return resolve(false)

            // 没有选择团队
            if (!saveForm.data.teamId) {
                const organ = treeOption.data.find(item => item.organizationId === saveForm.data.organizationId)
                if (!organ || (organ.teams && organ.teams.length)) return resolve(false)
            }

            // 请求
            const id = forbid.teamName ? saveForm.data.teamId! : saveForm.data.organizationId
            from(ApiDataSourceConfigTeam.delete(id))
                .pipe(map((data) => data))
                .pipe(mergeMap((data) => from(ASIDE_LIST_TREE()).pipe(map(() => data))))
                .subscribe({
                    next() {
                        ElMessage.success({ message: "删除成功", plain: true })
                        saveForm.reset()
                    },
                    async error(error) {
                        ElMessage.error({ message: '删除失败', plain: true })
                        await ASIDE_LIST_TREE()
                        reject(error)
                    },
                    complete() {
                        resolve(true)
                    }
                })
        })
    }

    // API:数据源权限
    function TABLE_GET_DATA_SOURCE_LIST() {
        return new Promise<boolean>((resolve, reject) => {
            const params: ParamDataSourceConfigTeamGetDataSourceList = {
                page: tableOptionSourceList.paginationConfig.currentPage,
                size: tableOptionSourceList.paginationConfig.pageSize,
                teamId: saveForm.data.teamId
            }

            // 请求
            from(ApiDataSourceConfigTeam.getDataSourceList(params))
                .pipe(map((data) => data))
                .subscribe({
                    next(data) {
                        tableOptionSourceList.data = data.records
                        tableOptionSourceList.paginationConfig.total = data.total
                    },
                    error(error) {
                        console.error(error)
                        reject(error);
                    },
                    complete() {
                        fullscreenLoading.value = false
                        resolve(true)
                    }
                })
        })
    }

    // API:用户信息
    function TABLE_GET_USER_LIST() {
        return new Promise<boolean>((resolve, reject) => {
            from(ApiDataSourceConfigTeam.userList())
                .pipe(map((data) => data))
                .subscribe({
                    next(data) {
                        tableOptionUserList.data = data
                    },
                    error(error) {
                        console.error(error)
                        reject(error);
                    },
                    complete() {
                        resolve(true)
                    }
                })
        })
    }

    // 流程执行
    new Observable((observer) => { observer.next(0); observer.complete() })
        .pipe(mergeMap(() => (async () => fullscreenLoading.value = true)()))
        .pipe(mergeMap(() => ASIDE_LIST_TREE()))
        .pipe(mergeMap(() => TABLE_GET_DATA_SOURCE_LIST()))
        .pipe(mergeMap(() => TABLE_GET_USER_LIST()))
        .subscribe({ complete: () => fullscreenLoading.value = false })
</script>

<style lang="scss" scoped>

    // 容器
    .custom__container {
        height: 100%;
        width: 100%;
        position: relative;
    }

    // 左侧
    .custom__aside {
        background: #fff;
        height: 100%;
        width: 100%;

        // 头部
        .custom__aside-header {
            padding: 10px;
            padding-bottom: 0px;
        }


        // 分割线
        .custom__aside-divider {
            margin-bottom: 5px;
        }

        // 内容
        .custom__aside-content {
            box-sizing: border-box;
            padding: 10px;
            padding-top: 5px;
            height: calc(100% - 94px);
            overflow-y: auto;
        }

    }

    // 主要内容
    .custom__main {
        padding: 0;
        padding-left: 10px
    }
</style>
